"use client";

import type { Dept } from "@/lib/api/system/dept.d";
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
  ProTableProps,
} from "@ant-design/pro-components";
import { Button, message, Popconfirm, Space, Tag } from "antd";
import { useRouter } from "next/navigation";
import { useRequest } from "ahooks";
import { useRef } from "react";
import { deleteDeptApi, getDeptListApi } from "@/lib/api/system/dept";
import { arrayToTree, dropTreeChildren } from "@/lib/utils/flat";

export default function Dept() {
  const router = useRouter();
  const actionRef = useRef<ActionType>();

  const { run: deleteDept } = useRequest(deleteDeptApi, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      actionRef.current?.reload();
    },
    onError: () => {
      message.error("删除失败");
    },
  });

  const colums: ProColumns<Dept>[] = [
    {
      title: "部门名称",
      dataIndex: "deptName",
      key: "deptName",
    },
    {
      title: "编码类型",
      dataIndex: "deptCategory",
      key: "deptCategory",
    },
    {
      title: "排序",
      dataIndex: "orderNum",
      key: "orderNum",
      search: false,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      valueEnum: {
        "0": "启用",
        "1": "停用",
      },
      render: (_, record) => (
        <Tag color={record.status === "0" ? "green" : "red"}>
          {record.status === "0" ? "正常" : "停用"}
        </Tag>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      valueType: "dateTime",
      width: 150,
      hideInSearch: true,
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => editHandler(record.deptId)}>
            修改
          </Button>
          <Popconfirm
            title="确定删除吗？"
            description="删除后将无法恢复！"
            onConfirm={() => {
              deleteDept(record.deptId);
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const proTableProps: ProTableProps<Dept, any> = {
    columns: colums,
    rowKey: "deptId",
    pagination: false,
    headerTitle: "部门列表",
    expandable: {
      defaultExpandAllRows: true,
    },
    actionRef: actionRef,
    options: {
      fullScreen: true,
    },
    toolBarRender: () => {
      return [
        <Button onClick={() => addHandler()} key="add" type="primary">
          新增
        </Button>,
      ];
    },
    request: async (params) => {
      const res = await getDeptListApi(params);

      const deptTree = arrayToTree(res.data, "deptId", "parentId");

      return {
        data: dropTreeChildren(deptTree),
        success: true,
      };
    },
    onRequestError(e) {
      message.error(e.message);
    },
  };

  const addHandler = (deptId?: string) => {
    router.push(`dept/add?deptId=${deptId}`);
  };

  const editHandler = (deptId: number) => {
    router.push(`dept/edit?deptId=${deptId}`);
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <ProTable {...proTableProps}></ProTable>
    </PageContainer>
  );
}
